# -*- coding: utf-8 -*-
# @Author: richardzgt﻿​
# @Date:   2018-06-26 17:47:38
# @Last Modified by:   richardzgt﻿​
# @Last Modified time: 2018-06-28 11:46:50
# 自动创建触发器

from zabbix.api import ZabbixAPI
from pyzabbix import ZabbixMetric, ZabbixSender
import json
import re
import sys,datetime
import logging

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO,
                format='%(levelname)s [%(asctime)s] [%(pathname)s L%(lineno)d] %(message)s')


class zbx_api(object):
    """docstring for zbx_del_host"""
    def __init__(self,url,user,passwd):
        try:
            self.zapi = ZabbixAPI(url=url,user=user,password=passwd)             
        except Exception as e:
            logger.error(e)

    def get_id_by_hostname(self,hostname):
        self.host = hostname
        get_host_by_name = self.zapi.do_request('host.get',
                    {
                        'filter': {'host':[self.host]},
                        'output': 'extend',
                    })
   

        if len(get_host_by_name['result']) > 0:
            try:
                self.hostid = get_host_by_name['result'][0]['hostid']
            except Exception as e:
                logger.error(e)
                # sys.exit(3)

    def get_item_info(self,item_name):
        getItem = self.zapi.do_request('item.get',
                                {
                                    'hostids': self.hostid,
                                    'search': {'key_':item_name},
                                    'output': 'extend',
                                })
        try:
            logger.debug(getItem['result'])
            self.itemid = getItem['result'][0]['itemid']
            self.item = getItem['result'][0]['key_']
            self.item_key_name = re.match(r"bmt.\[(.+)\]",getItem['result'][0]['key_']).groups()[0]
        except Exception as e:
            logger.error( "%s: %s" % (item_name,e))
            # sys.exit(3)

    def get_nodata_trg_id(self):
        getTrigger = self.zapi.do_request('trigger.get',
                            {
                                'filter': {
                                        'hostid':self.hostid,
                                        'search':{'description':'bmt.[%s]' % self.item_key_name},
                                        'output': 'extend',
                                }
                            })
        for each in getTrigger['result']:
            if "BM NO Data Alert: %s" % self.item_key_name in each['description']:
                self.no_data_trg_id = each['triggerid']
                logger.debug(self.no_data_trg_id)
                break

    def wrapper_trigger(self,express):
        #格式： 表达式 操作符 值
        # min(#2)}>100
        try:
            _key = re.match(r"(?P<func>.+?)(?P<op>[><=]{1,2})(?P<value>\d+)",express).groupdict()
            self.expression = "{%s:bmt.[%s].%s}%s%s"  % (self.tgt_host,
                                                            self.item_key_name,
                                                            _key['func'],
                                                            _key['op'],
                                                            _key['value'])

            logger.debug(self.expression)
        except Exception as e:
            pass
        

    def create_trigger(self,tgt_host,item_name,comments,express):
        self.tgt_host = tgt_host
        self.get_id_by_hostname(tgt_host)
        self.get_item_info(item_name)
        self.get_nodata_trg_id()
        self.wrapper_trigger(express)
        try:
            createTriger = self.zapi.do_request('trigger.create',
                                    {
                                        "hostid": self.hostid,
                                        "description": "BM_Alert_%s Exceed[$1]" % self.item_key_name,
                                        "expression":self.expression,
                                        "priority": 4,
                                        "comments": comments,
                                        "dependencies": [
                                            {"triggerid":self.no_data_trg_id}
                                        ]
                         })   
        except Exception as e:
            pass

if __name__ == '__main__':
    z = zbx_api(url='http://192.168.17.110/', user='admin', passwd='XXXX')
    # 监控项名称(搜索) 备注(告警短信内容) 表达式
    with open('triggers.txt','r') as f:
        for each in f:
            if len(each) > 1:
                item_name, comments, express = each.strip().split('|')
                # print item_name,express,comments
                z.create_trigger(
                    tgt_host="88lm-webpd-1-1.server.dt",
                    item_name=item_name,
                    express=express,
                    comments=comments,
                    )